package com.orkhonsoft.tengrinshar.chat.config;

import javax.servlet.MultipartConfigElement;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration  
public class UploadFileConfiguration extends WebMvcConfigurerAdapter{  
	@Value("${cbs.imagesPath}")
    private String mImagesPath;
    @Bean  
    public MultipartConfigElement multipartConfigElement() {  
        MultipartConfigFactory factory = new MultipartConfigFactory();  
        factory.setMaxFileSize("10MB");  
        factory.setMaxRequestSize("10MB");  
        return factory.createMultipartConfig();  
    }  
    
    /**
     * @Description: 对文件的路径进行配置,创建一个虚拟路径/Path/** ，即只要在<img src="/Path/picName.jpg" />便可以直接引用图片
     *这是图片的物理路径  "file:/+本地图片的地址"
     * @Date： Create in 14:08 2017/12/20
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {   
    	if(mImagesPath.equals("") || mImagesPath.equals("${cbs.imagesPath}")){
            String imagesPath = UploadFileConfiguration.class.getClassLoader().getResource("").getPath();
            if(imagesPath.indexOf(".jar")>0){
             imagesPath = imagesPath.substring(0, imagesPath.indexOf(".jar"));
            }else if(imagesPath.indexOf("classes")>0){
             imagesPath = "file:"+imagesPath.substring(0, imagesPath.indexOf("classes"));
            }
            imagesPath = imagesPath.substring(0, imagesPath.lastIndexOf("/"))+"/images/";
            mImagesPath = imagesPath;
           }
           LoggerFactory.getLogger(UploadFileConfiguration.class).info("imagesPath="+mImagesPath);
           registry.addResourceHandler("/images/**").addResourceLocations(mImagesPath);
     // TODO Auto-generated method stub
     super.addResourceHandlers(registry);
    }
    
}  